One of the most basic operations in programming is iterating over a list of elements to perform some kind of operation.
In python we use the for
statement to iterate. It is easier to use than the same statement in C, C++ or FORTRAN because instead of running over a integer index it takes as an input any iterable object and runs over it.
Let's see some examples
In [ ]:
a = [4,5,6,8,10]
for i in a:
print(i)
In [ ]:
# A fragment of `One Hundred Years of Solitude`
GGM = 'Many years later, as he faced the firing squad, \
Colonel Aureliano Buendía was to remember that dist \
ant afternoon when his father took him to discover ice. \
At that time Macondo was a village of twenty adobe houses,\
built on the bank of a river of clear water that ran along \
a bed of polished stones, which were white and enormous,\
like prehistoric eggs.'
print(GGM)
In [ ]:
dot = GGM.split() # we create a list where each element is a word
print(dot)
for i in dot:
print(i)
In [ ]:
a = {} # empty dictionary
a[1] = 'one'
a[2] = 'two'
a[3] = 'three'
a[4] = 'four'
a[5] = 'five'
print(a)
In [ ]:
for k in a.keys(): # iterate over the keys
print(a[k])
In [ ]:
for v in a.values(): #iterate over the values
print(v)
In [ ]:
print(range(10)) # range itself returns an iterable object
a = list(range(10)) # this translates that iterable object into a list
print(a) # be careful! the lists has 10 objects starting with 0
In [ ]:
for i in range(10): # if you given a single argument the iterations starts at 0.
print(i)
In [ ]:
for i in range(4,10): # you can algo give two arguments: range(start, end).
print(i)
In [ ]:
for i in range(0,10,3): # if you give three arguments they are interpreted as range(start, end, step)
print(i)
In [ ]:
In [ ]:
In [ ]: